import { loginAPI, getUserProfileAPI, getUserInfoAPI } from '@/api/user'
import { setToken as setTokenToCookie, getToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setTokenToCookie(newToken)
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  logout(state) {
    state.token = ''
    removeToken()
    state.userInfo = {}
  }
}
const actions = {
  login(store, data) {
    // 使用Promise封装的目的： 让组件内部拿到接口响应结果之后 ，才进行跳转
    return new Promise((resolve, reject) => {
      loginAPI(data).then((res) => {
        store.commit('setToken', res.data)
        resolve(res)
      }).catch(err => {
        console.log(err.message)
        reject(err)
      })
    })
  },
  async getUserProfile({ commit }) {
    const res = await getUserProfileAPI()
    const res2 = await getUserInfoAPI(res.data.userId)
    const baseInfo = {
      ...res.data,
      ...res2.data
    }
    commit('setUserInfo', baseInfo)
    return baseInfo
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
